package com.ivo.sys;

import java.util.List;

import com.ivo.biz.Permissions;
import com.ivo.sec.SessionLocal;
import com.ivo.sys.user.Role;
import com.ivo.sys.user.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 
 *
 * @author Minkey Wang
 * @version 2017年7月8日
 */
@Service
public class CodeService {
	@Autowired
	CodeManager codeManager;
	
	@Autowired
	private UserService userService;
	
	public List<Code> list() {
		String hql = "from Code c where c.isValid = true ";
		String user_id = SessionLocal.getUser().getUser_id();
		Role role = userService.getRoleByUser(user_id);
		if(SessionLocal.getUser()!=null){
			if(!SessionLocal.getUser().getFactory().equals("WH") && !SessionLocal.getUser().getFactory().equals("CEL") && !role.getName().equals("admin")){
				Permissions pms = userService.getPermissionsByUser(SessionLocal.getUser().getUser_id());
				if(pms != null){
					String operations = pms.getOpe_fk().trim().replace(" ", ",");
					hql = hql + " and c.id in (" + operations + ")";
				}else{
					hql = hql + " and c.id = '9999'";
				}
				
			}
		}
		return codeManager.find(hql);
	}
	
	
	public List<Code> dustfreeAndmajorlist() {
		String hql = "from Code c where c.isValid = true ";
		String user_id = SessionLocal.getUser().getUser_id();
		if(SessionLocal.getUser()!=null){
			/*if(SessionLocal.getUser().getFactory().contains("M")){
				
			}else */
			if(SessionLocal.getUser().getFactory().equals("ARY")){
				Permissions pms = userService.getPermissionsByUser(SessionLocal.getUser().getUser_id());
				if(pms != null){
					String operations = pms.getOpe_fk().trim().replace(" ", ",");
					hql = hql + " and c.id in (" + operations + ")";
				}else{
					hql = hql + " and c.id = '9999'";
				}
			}
		}
		return codeManager.find(hql);
	}
	
	
	public Code getCode(String name){
		String hql = "select u from Code u  where u.isValid=true and u.name=?0 ";
		return codeManager.findUnique(hql, name);
	}
	
	public Code getCELCodeByLabel(String label){
		String hql = "select u from Code u  where u.isValid=true and u.label=?0  and u.category=5";
		return codeManager.findUnique(hql, label);
	}
}
